import json

from django import http
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import SKU
from utils.cookiesecret import CookieSecret
from utils.response_code import RETCODE


class CartsView(View):

    def get(self,request):

        user=request.user
        if user.is_authenticated:
            # 1.用户已登录，查询redis购物车
            carts_redis_client = get_redis_connection('carts')

            # 2.获取当前用户的 所有购物车数据
            carts_data = carts_redis_client.hgetall(user.id)

            # 3.转换格式-->和cookie一样的字典 方便后面构建数据
            carts_dict = {int(data[0].decode()): json.loads(data[1].decode()) for data in carts_data.items()}
        else:
            # 1. 用户未登录，查询cookies购物车
            cookie_str=request.COOKIES.get('carts')
            # 2. 判断是否有值 : 有 ---解密==>dict
            if cookie_str:
                carts_dict=CookieSecret.loads(cookie_str)
            else:
                carts_dict={}

        sku_ids = carts_dict.keys()

        skus = SKU.objects.filter(id__in=sku_ids)
        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': carts_dict.get(sku.id).get('count'),
                'selected': str(carts_dict.get(sku.id).get('selected')),  # 将True，转'True'，方便json解析
                'default_image_url': sku.default_image.url,
                'price': str(sku.price),  # 从Decimal('10.2')中取出'10.2'，方便json解析
                'amount': str(sku.price * carts_dict.get(sku.id).get('count')),
            })

        context = {
            'cart_skus': cart_skus,
        }

        # 渲染购物车页面
        return render(request, 'cart.html', context)

    def post(self, request):

        # 1.接收参数 request.body
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        # 2.校验
        if not all([sku_id, count]):
            return http.HttpResponseForbidden('缺少必传参数')
            # 判断sku_id是否存在
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品不存在')

        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return http.HttpResponseForbidden('参数count有误')

        # 判断selected是否为bool值
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')

        # 3.判断是否登录
        user = request.user
        if user.is_authenticated:
            # 3.1 登录 redis
            # 3.2 判断 当前用户 是否 有购物记录  如果没有 就新建一条记录
            client_redis = get_redis_connection('carts')
            # print(client_redis.hgetall())
            client_data = client_redis.hgetall(user.id)

            print("client_data",client_data)

            if not client_data:
                # 新建一条记录
                client_redis.hset(user.id, sku_id, json.dumps({'count': count, 'selected': selected}))

            # 3.3 如果有记录----sku_id:count+=1   --- count+=1
            if str(sku_id).encode() in client_data:

                sku_dict = json.loads(client_data[str(sku_id).encode()].decode())

                print("sku_dict",sku_dict)
                sku_dict['count'] += count
                # 3.4 遍历 获取到的数据 每一个商品sku_id  判断 那个是传入的商品
                # 3.5 count+=1
                # 3.6 修改整个商品
                client_redis.hset(user.id, sku_id, json.dumps(sku_dict))

            else:
                client_redis.hset(user.id, sku_id, json.dumps({'count': count, 'selected': selected}))



            return JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})
        else:
            # 3.2 未登录 cookie

            cookie_str=request.COOKIES.get('carts')

            if cookie_str:
                carts_dict=CookieSecret.loads(cookie_str)
            else:
                carts_dict={}

            print("cookie carts_dict 修改前", carts_dict)

            if sku_id in carts_dict:
                original_count=carts_dict[sku_id]['count']
                count=original_count+count

            carts_dict[sku_id]={
                'count':count,
                'selected':selected
            }
            print("cookie carts_dict 修改后", carts_dict)
            cookie_secret_str=CookieSecret.dumps(carts_dict)

            response = JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})
            response.set_cookie('carts', cookie_secret_str, max_age=14 * 24 * 3600)

            # 5. 返回响应
            return response

    def put(self, request):
        """修改购物车"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        # 判断参数是否齐全
        if not all([sku_id, count]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 判断sku_id是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品sku_id不存在')
        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return http.HttpResponseForbidden('参数count有误')
        # 判断selected是否为bool值
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')

        # 判断用户是否登录
        user = request.user
        cookie_secret_str = ''
        # 接收cookie最后的数据
        cookie_cart_str = ""
        if user.is_authenticated:
            # 用户已登录，修改redis购物车
            redis_client=get_redis_connection('carts')
            new_data={'count':count,'selected':selected}
            redis_client.hset(user.id,sku_id,json.dumps(new_data))
        else:
            # 用户未登录，修改cookie购物车
            # *   1.取出cookie
            cookie_str=request.COOKIES.get('carts')
            # *   2.判断有无 有--解密
            if cookie_str:
                cart_dict=CookieSecret.loads(cookie_str)
            else:
                cart_dict={}

            # *   3. 修改 dict[k]=count
            cart_dict[sku_id]={
                'count':count,
                'selected':selected
            }
            # *   4. cookes_str --加密
            cookie_cart_str=CookieSecret.dumps(cart_dict)


        # 构建前端的数据格式
        cart_sku = {
            'id': sku_id,
            'count': count,
            'selected': selected,
            'name': sku.name,
            'default_image_url': sku.default_image.url,
            'price': sku.price,
            'amount': sku.price * count,
        }

        response = JsonResponse({'code': RETCODE.OK, 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})
        # 未登录 才设置cookie
        if not user.is_authenticated:
            response.set_cookie('carts', cookie_cart_str)
        return response

    def delete(self, request):
        """删除购物车"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')

        # 判断sku_id是否存在
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品不存在')

        # 判断用户是否登录
        user = request.user
        if user is not None and user.is_authenticated:
            # 用户未登录，删除redis购物车
            redis_client = get_redis_connection('carts')
            redis_client.hdel(user.id,sku_id)
            # 删除结束后，没有响应的数据，只需要响应状态码即可
            return JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车成功'})
        else:
            # 用户未登录，修改cookie购物车
            # *   1.取出cookie
            cookie_str = request.COOKIES.get('carts')
            # *   2.判断有无 有--解密
            if cookie_str:
                cart_dict = CookieSecret.loads(cookie_str)
            else:
                cart_dict = {}

            # 创建响应对象
            response = JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车成功'})
            if sku_id in cart_dict:
                # 删除数据
                del cart_dict[sku_id]
                # 将字典转成密文
                cookie_cart_str = CookieSecret.dumps(cart_dict)
                # 响应结果并将购物车数据写入到cookie
                response.set_cookie('carts', cookie_cart_str, max_age=14 * 30 * 3600)
            return response


class CartsSelectAllView(View):
    """全选购物车"""

    def put(self, request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get('selected', True)

        # 校验参数
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')

        # 判断用户是否登录
        user = request.user
        if  user.is_authenticated:
            # 用户已登录，操作redis购物车
            client_redis = get_redis_connection('carts')
            client_data = client_redis.hgetall(user.id)

            for cart in client_data.items():
                sku_id=cart[0].decode()
                cart_dict = json.loads(cart[1].decode())
                if selected:
                    cart_dict["selected"]=True
                else:
                    cart_dict["selected"]=False

                client_redis.hset(user.id,sku_id,json.dumps(cart_dict))

            return JsonResponse({'code': RETCODE.OK, 'errmsg': '全选购物车成功'})
        else:
            # 用户未登录，操作cookie购物车
            # 用户未登录，操作cookie购物车
            carts_str = request.COOKIES.get('carts')
            response = JsonResponse({'code': RETCODE.OK, 'errmsg': '全选购物车成功'})
            if carts_str is not None:
                carts_dict=CookieSecret.loads(carts_str)
                for sku_id in carts_dict:
                    carts_dict[sku_id]['selected'] = selected

                cookie_cart = CookieSecret.dumps(carts_dict)
                response.set_cookie('carts', cookie_cart, 24 * 30 * 3600)
            return response

class CartsSimpleView(View):
    def get(self, request):

        user = request.user
        if user.is_authenticated:
            # redis 3
            redis_client = get_redis_connection('carts')
            client_data = redis_client.hgetall(user.id)
            carts_dict = {int(data[0].decode()): json.loads(data[1].decode()) for data in client_data.items()}
        else:

            # cookie 5.
            cookie_str = request.COOKIES.get('carts')
            if cookie_str:
                carts_dict = CookieSecret.loads(cookie_str)
            else:
                carts_dict = {}

        cart_skus = []
        sku_ids = carts_dict.keys()
        skus = SKU.objects.filter(id__in = sku_ids)
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': carts_dict.get(sku.id).get('count'),
                'default_image_url': sku.default_image.url
            })

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'cart_skus': cart_skus})
